package com.hawk.eye.server.controller.hawkeye;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hawk.eye.common.core.ApiResult;
import com.hawk.eye.framework.utils.CollectionUtil;
import com.hawk.eye.framework.utils.ExceptionUtils;
import com.hawk.eye.server.constant.GroupConstant;
import com.hawk.eye.server.convert.GroupConvert;
import com.hawk.eye.server.domain.dto.resp.ServiceConfigRespDTO;
import com.hawk.eye.server.domain.dto.resp.TreeRespDTO;
import com.hawk.eye.server.domain.po.Group;
import com.hawk.eye.server.domain.vo.req.GroupReqVO;
import com.hawk.eye.server.domain.vo.resp.GroupRespVO;
import com.hawk.eye.server.domain.vo.resp.TreeRespVO;
import com.hawk.eye.server.service.IServiceConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hawk.eye.server.service.IGroupService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * 告警配置分组 Controller
 *
 * @author salad
 * @date 2023-09-23
 */
@Slf4j
@RestController
@RequestMapping("/hawk-eye/group")
@RequiredArgsConstructor
public class GroupController {

    private final IGroupService groupService;

    private final IServiceConfigService serviceConfigService;

    /**
     * 查询分组树结构数据
     *
     * @param reqVo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hawk-eye:service-config:query')")
    @GetMapping(value = "/tree")
    public ApiResult<List<TreeRespVO>> tree(GroupReqVO reqVo) {
        List<TreeRespDTO> tree = groupService.list(GroupConvert.INSTANCE.reqVoToReqDto(reqVo));
        return ApiResult.ok(GroupConvert.INSTANCE.dtoTreeToVoTreeList(tree));
    }

    /**
     * 查询分组列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hawk-eye:service-config:query')")
    @GetMapping(value = "/list")
    public ApiResult<List<GroupRespVO>> list() {
        GroupConstant[] values = GroupConstant.values();
        List<Group> groups = groupService.list(Wrappers.<Group>lambdaQuery()
                .orderByAsc(Group::getGroupName).orderByAsc(Group::getCreateTime));
        List<GroupRespVO> respVOList = new ArrayList<>();
        Stream.of(values).forEach(group -> {
            respVOList.add(new GroupRespVO(group.getValue(), group.getName()));
        });
        respVOList.addAll(GroupConvert.INSTANCE.poToRespVoList(groups));
        return ApiResult.ok(respVOList);
    }

    /**
     * 新增分组
     *
     * @param reqVO
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hawk-eye:service-config:add')")
    @PostMapping("/save")
    public ApiResult save(@RequestBody @Validated GroupReqVO reqVO) {
        boolean status = groupService.save(GroupConvert.INSTANCE.reqVoToReqDto(reqVO));
        return ApiResult.status(status);
    }


    /**
     * 分组详情
     *
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hawk-eye:service-config:query')")
    @GetMapping(value = "detail/{id}")
    public ApiResult detail(@PathVariable("id") Long id) {
        return ApiResult.ok(groupService.detail(id));
    }

    /**
     * 修改分组
     *
     * @param reqVO
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hawk-eye:service-config:edit')")
    @PutMapping("/update")
    public ApiResult update(@RequestBody GroupReqVO reqVO) {
        return ApiResult.status(groupService.update(GroupConvert.INSTANCE.reqVoToReqDto(reqVO)));
    }

    /**
     * 删除分组
     *
     * @param ids
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hawk-eye:service-config:remove')")
    @DeleteMapping("/remove/{ids}")
    public ApiResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            ExceptionUtils.isTrueThrow(id == 0, "默认分组不可删除");
            //存在子节点不允许删除
            List<ServiceConfigRespDTO> scs = serviceConfigService.getServiceConfigByGroup(id);
            if (CollectionUtil.isNotEmpty(scs)) {
                Group group = groupService.getById(id);
                throw ExceptionUtils.error("分组[{}]下存在服务配置，不允许删除", group.getGroupName());
            }
        }
        return ApiResult.status(groupService.removeBatchByIds(CollectionUtil.toList(ids)));
    }

}
